<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\Database\Model\Builder;

/**
 * 优惠券model
 *
 * @Author czm
 * @DateTime 2020-04-16
 */
class CouponBatch extends Model
{
    
    use SelectTrait;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'coupon_batch';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name','batch','number','amount','status','type','condition_amount','start_time','end_time','add_time','update_time','is_del'];
    protected $guarded=['id'];
    protected $hidden = ['is_del'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'add_time'=>'datetime:Y-m-d H:i:s',
        'update_time'=>'datetime:Y-m-d H:i:s',

    ];

    const CREATED_AT = 'add_time';
    const UPDATED_AT = 'update_time';
    const DELETED_AT = 'delete_time';



    protected $dateFormat = 'U';

    protected function boot(): void
    {   
        $this->bootTraits();
        //model 软删除过滤 避免每次查询都添加is_del条件 去除条件添加withoutGlobalScope
        $this->addGlobalScope('is_del', function(Builder $builder) {
            $builder->where($this->table.'.is_del',1);
        });
        // var_dump($columns);
    }
  

    

    //一对多获取红包
    public function coupon(){
       return  $this->hasMany(Coupon::class,'batch_id','id');
    }

    //映射type
    public function getTypeMappingAttribute(){
        switch($this->attributes['type']){
            case 1:$val='充值抵扣卷'; break;
            case 2:$val='减至券';break;
            case 3:$val='兑换券';break;
            default:$val='';break;

        }
        return $val;
    }

    //映射status
    public function getStatusMappingAttribute(){
      
        switch($this->attributes['status']){
            case 1:$val='未使用';break;
            case 2:$val='已使用';break;
            default:  $val='';break;
        }
        return $val;
    }

     

    //映射批次时间状态
    public function getTimeMappingAttribute(){
        $now=time();
        $val="可用";
        if($now<$this->attributes['start_time']){
            $val="未生效";
        }
        if($now>$this->attributes['end_time']){
            $val="已过期";
        }
        return $val;
    }   
}